package com.hjs.community.search.service;

import com.alibaba.fastjson.JSON;
import com.hjs.community.search.dto.PostDTO;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SearchPostService {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @Value("${community.post.indexName}")
    private String indexName;

    @Value("${community.post.typeName}")
    private String typeName;

    /**
     * 给es中添加帖子
     */
    public void addPost(PostDTO postDTO) throws Exception {
        IndexRequest request = new IndexRequest();
        request.index(indexName);
        request.type(typeName);
        request.source(JSON.toJSONString(postDTO), XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 根据关键字到es中查询
     */
    public List<PostDTO> searchPostList(String keyword) throws Exception {
        SearchRequest request = new SearchRequest(indexName);
        request.types(typeName);

        // 添加查询的条件
        SearchSourceBuilder builder = SearchSourceBuilder.searchSource();
        // 话题，标题，内容中出现了关键字就匹配到
        builder.query(QueryBuilders.multiMatchQuery(keyword, "discussList", "title", "content"));

        // 把查询条件设置到req对象中
        request.source(builder);
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();

        List<PostDTO> list = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            String sourceAsString = hits[i].getSourceAsString();
            list.add(JSON.parseObject(sourceAsString, PostDTO.class));
        }
        return list;
    }

    public void createPostIndex() throws Exception {

        CreateIndexRequest request = new CreateIndexRequest();
        request.index(indexName);

        //1. settings
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 3)
                .put("number_of_replicas", 1);

        //2. mapping.
        XContentBuilder mapping = JsonXContent.contentBuilder()
                .startObject()
                .startObject("properties")
                .startObject("userId")
                .field("type", "integer")
                .endObject()
                .startObject("classId")
                .field("type", "integer")
                .endObject()
                .startObject("topicId")
                .field("type", "integer")
                .endObject()
                .startObject("type")
                .field("type", "integer")
                .endObject()

                .startObject("seeNum")
                .field("type", "integer")
                .endObject()

                .startObject("thumbNum")
                .field("type", "integer")
                .endObject()

                .startObject("commentNum")
                .field("type", "integer")
                .endObject()
                .startObject("discussList")
                .field("type", "text")
                .field("analyzer", "ik_max_word")
                .endObject()
                .startObject("title")
                .field("type", "text")
                .field("analyzer", "ik_max_word")
                .endObject()
                .startObject("content")
                .field("type", "text")
                .field("analyzer", "ik_max_word")
                .endObject()
                .startObject("media")
                .field("type", "keyword")
                .endObject()
                .startObject("createTime")
                .field("type", "date")
                .endObject()
                .endObject()
                .endObject();

        request.settings(settings);
        request.mapping(typeName, mapping);

        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
    }

    public boolean hasExists(String indexName) throws Exception {
        GetIndexRequest getRequest = new GetIndexRequest();
        getRequest.indices(indexName);
        return client.indices().exists(getRequest, RequestOptions.DEFAULT);
    }
}
